//
//  IQAlbumAssetsViewController.m
//  https://github.com/hackiftekhar/IQMediaPickerController
//  Copyright (c) 2013-14 Iftekhar Qurashi.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.

// 版权属于原作者
// http://code4app.com (cn) http://code4app.net (en)
// 发布代码于最专业的源码分享网站: Code4App.com


#import "IQAlbumAssetsViewController.h"
#import "IQAssetsCell.h"
#import "IQAssetsPickerController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "IQMediaPickerControllerConstants.h"

#import "UIView+DDAddition.h"
#import "UIButton+HYYImagePosition.h"

//预览
#import "PhotoViewerVC.h"
#import "GlobalUtil.h"
#import "FormatUtil.h"
#import "StringUtil.h"
#import "ToastView.h"

@interface IQAlbumAssetsViewController () <UICollectionViewDelegateFlowLayout,UIGestureRecognizerDelegate, PhotoViewVCDelegate>
{
    BOOL _isPlayerPlaying;
    UIImage *_selectedImageToShare;
}

@property(nonatomic, strong) NSMutableIndexSet *selectedAssets;
@property(nonatomic, assign) BOOL isOriginalPic;
@property(nonatomic, retain) UIButton *originalBtn;
@property(nonatomic, retain) UIButton *preViewBtn;
@property(nonatomic, retain) UIButton *confirmBtn;
@end

@implementation IQAlbumAssetsViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    
    NSInteger cellW = (NSInteger)(self.collectionView.width - 12.0)/4;
    
    UICollectionViewFlowLayout *_flowLayout = (UICollectionViewFlowLayout*)self.collectionViewLayout;
    _flowLayout.minimumLineSpacing = 2.0f;
    _flowLayout.minimumInteritemSpacing = 2.0f;
    _flowLayout.sectionInset = UIEdgeInsetsMake(5.0f, 2.0f, 5.0f, 2.0f);
    _flowLayout.itemSize = CGSizeMake(cellW, cellW);

    [self.collectionView registerClass:[IQAssetsCell class] forCellWithReuseIdentifier:@"cell"];
    self.collectionView.alwaysBounceVertical = YES;

    self.title = [self.assetsGroup valueForProperty:ALAssetsGroupPropertyName];
    
    _selectedAssets = [[NSMutableIndexSet alloc] init];
    
    if (_pickerType == IQAssetsPickerControllerAssetTypeVideo)
    {
        UILongPressGestureRecognizer *longPressGesture = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPressGestureRecognizer:)];
        [self.collectionView addGestureRecognizer:longPressGesture];
        longPressGesture.delegate = self;
    }
    
    _isOriginalPic = NO;
    
    if (self.assetController.allowsPickingMultipleItems == YES)
    {
        [self createBottomBar];
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self scrollToLastIndexPath];
}


- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self scrollToLastIndexPath];
}

- (void)scrollToLastIndexPath
{
    NSInteger section = [self.collectionView numberOfSections] - 1;
    NSInteger item = [self.collectionView numberOfItemsInSection:section] - 1;
    
    if (section >= 0 && item >= 0)
    {
        NSIndexPath *lastIndexPath = [NSIndexPath indexPathForItem:item inSection:section];
        [self.collectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
        [self.collectionView scrollToItemAtIndexPath:lastIndexPath atScrollPosition:UICollectionViewScrollPositionBottom animated:NO];
        
    }
}

- (void)createBottomBar {
    UIView *bottomBar = [[UIView alloc] initWithFrame:CGRectMake(0, UI_CONTENT_HEIGHT - TabBar_Height, UI_SCREEN_WIDTH, TabBar_Height)];
    bottomBar.backgroundColor = RGB(246, 246, 246);
    
    UIFont *btnNameFont = [UIFont systemFontOfSize:16.0f];
    
    UIButton *albumBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    albumBtn.frame = CGRectMake(0, 0, 45.0f, 30.0f);
    [albumBtn setTitle:@"相册" forState:UIControlStateNormal];
    [albumBtn setTitleColor:[EPColor epColor_Blue] forState:UIControlStateNormal];
    albumBtn.titleLabel.font = btnNameFont;
    [albumBtn addTarget:self action:@selector(onClickAlbumBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.preViewBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.preViewBtn.frame = CGRectMake(0, 0, 45.0f, 30.0f);
    [self.preViewBtn setTitle:@"预览" forState:UIControlStateNormal];
    [self.preViewBtn setTitle:@"预览" forState:UIControlStateDisabled];
    [self.preViewBtn setTitleColor:[EPColor epColor_Blue] forState:UIControlStateNormal];
    [self.preViewBtn setTitleColor:RGB(0x99, 0x99, 0x99) forState:UIControlStateDisabled];
    self.preViewBtn.titleLabel.font = btnNameFont;
    [self.preViewBtn addTarget:self action:@selector(onClickPreViewBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    self.preViewBtn.enabled = NO;
    
    self.originalBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.originalBtn.frame = CGRectMake(0, 0, 150.0f, 30.0f);
    [self.originalBtn setImage:[UIImage imageNamed:@"artwork_uncheck"] forState:UIControlStateNormal];
    [self.originalBtn setImage:[UIImage imageNamed:@"artwork_checked"] forState:UIControlStateSelected];
    [self.originalBtn setTitle:@"原图" forState:UIControlStateNormal];
    [self.originalBtn setTitle:@"原图" forState:UIControlStateSelected];
    [self.originalBtn setTitleColor:[EPColor epColor_Blue] forState:UIControlStateNormal];
    [self.originalBtn setTitleColor:[EPColor epColor_Blue] forState:UIControlStateSelected];
    self.originalBtn.titleLabel.font = btnNameFont;
    self.originalBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    [self.originalBtn addTarget:self action:@selector(onClickOriginalBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.originalBtn setImagePosition:HYYImagePositionLeft spacing:5.0f];
    self.originalBtn.selected = _isOriginalPic;
    
    self.confirmBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.confirmBtn.frame = CGRectMake(0, 0, 80.0f, 30.0f);
    self.confirmBtn.backgroundColor = [UIColor lightGrayColor];
    [self.confirmBtn setTitle:@"选择" forState:UIControlStateNormal];
    [self.confirmBtn setTitle:@"选择" forState:UIControlStateDisabled];
    [self.confirmBtn setTitleColor:RGB(0xff, 0xff, 0xff) forState:UIControlStateNormal];
    [self.confirmBtn setTitleColor:[UIColor darkGrayColor] forState:UIControlStateDisabled];
    self.confirmBtn.titleLabel.font = btnNameFont;
    [self.confirmBtn addTarget:self action:@selector(onClickConfirmBtnAction:) forControlEvents:UIControlEventTouchUpInside];
    [GlobalUtil roundForView:self.confirmBtn withRadius:2.5f];
    self.confirmBtn.enabled = NO;
    
    albumBtn.left = 15.0f;
    albumBtn.centerY = (bottomBar.height - IPhoneX_FixHeight)/2;
    
    self.preViewBtn.left = albumBtn.right + 5.0f;
    self.preViewBtn.centerY = (bottomBar.height- IPhoneX_FixHeight)/2;
    
    self.originalBtn.left = self.preViewBtn.right + 5.0f;
//    self.originalBtn.left = albumBtn.right + IPHONE6_RETINAPX(10.0f);
    self.originalBtn.centerY = (bottomBar.height - IPhoneX_FixHeight)/2;
    
    self.confirmBtn.right = bottomBar.width - 15.0f;
    self.confirmBtn.centerY = (bottomBar.height - IPhoneX_FixHeight)/2;
    
    [bottomBar addSubview:albumBtn];
    [bottomBar addSubview:self.preViewBtn];
    [bottomBar addSubview:self.originalBtn];
    [bottomBar addSubview:self.confirmBtn];
    
    [self.view addSubview:bottomBar];
    self.collectionView.height = self.view.height - bottomBar.height;
}

- (void)onClickAlbumBtnAction:(UIButton *)sender {
    //TODO:相册
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)onClickPreViewBtnAction:(UIButton *)sender {
    //TODO:预览
    NSMutableArray *selectedImages = [[NSMutableArray alloc] init];
    NSMutableArray *selectedIndexs = [[NSMutableArray alloc] init];
    [self.assetsGroup enumerateAssetsAtIndexes:self.selectedAssets options:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
     {
         
         if (result)
         {
             if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
             {
                 ALAssetRepresentation *imageRep = [result defaultRepresentation];
                 
                 CGImageRef imageRef = [imageRep fullScreenImage];
                 UIImage *image = [UIImage imageWithCGImage:imageRef];
                 if (image == nil || image.size.width <= 0) {
                     return;
                 }
                 [selectedIndexs addObject:[NSString stringWithFormat:@"%ld",index]];
                 
                 [selectedImages addObject:image];
             }
         }
     }];
    
    PhotoViewerVC *photoVC = [[PhotoViewerVC alloc] init];
    photoVC.dataList = [selectedImages copy];
    photoVC.ablumIndexs = selectedIndexs;
    photoVC.delegate = self;
    photoVC.isShowPageNumLabel = YES;
    photoVC.isShowDeleBtn = YES;//删除，取消选中
    [self.navigationController pushViewController:photoVC animated:YES];
}

- (void)onClickOriginalBtnAction:(UIButton *)sender {
    sender.selected = !sender.selected;
    
    _isOriginalPic = sender.selected;
    
    [self setIsOriginalPic:sender.selected];
    if (_isOriginalPic == YES) {
        NSString *originalBtnName = @"原图";
        float totalSize = [self getSelectedSize];
        if (totalSize > 0) {
            originalBtnName = [NSString stringWithFormat:@"原图(%@)",[FormatUtil stringFromSize:[self getSelectedSize]]];
        }
        [self.originalBtn setTitle:originalBtnName forState:UIControlStateSelected];
    }
}

- (float)getSelectedSize {
    __block float totalSize = 0;
    if (self.selectedAssets.count <= 0) return 0;
    [self.assetsGroup enumerateAssetsAtIndexes:self.selectedAssets options:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
     {
         
         if (result)
         {
             if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
             {
                 ALAssetRepresentation *imageRep = [result defaultRepresentation];
                 totalSize += [imageRep size];
             }
             else if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo])
             {
                 ALAssetRepresentation *representation = [result defaultRepresentation];
                 totalSize += [representation size];
             }
         }
     }];
    
    return totalSize;
}

- (void)onClickConfirmBtnAction:(UIButton *)sender {
    
    NSMutableArray *selectedVideo = [[NSMutableArray alloc] init];
    NSMutableArray *selectedImages = [[NSMutableArray alloc] init];
    WEAKSELF
    [self.assetsGroup enumerateAssetsAtIndexes:self.selectedAssets options:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
     {
         
         if (result)
         {
             if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
             {
                 ALAssetRepresentation *imageRep = [result defaultRepresentation];
                 CGImageRef imageRef = [imageRep fullScreenImage];
                 
                 UIImage *image = [[UIImage alloc]initWithCGImage:imageRef];
//                 UIImageOrientation orientation = (UIImageOrientation)[imageRep orientation];
//                 UIImage *image = [[UIImage alloc] initWithCGImage:imageRef scale:1.0 orientation:orientation];

                 if (image == nil || image.size.width <= 0) {
                     return;
                 }
                 
                 if (weakSelf.isOriginalPic == NO) {
                     //压缩图片：
                     UIImage *finalImage = [weakSelf scaleImage:image toSize:weakSelf.maxImageSize];
                     NSString *imageFileName = [imageRep filename];
                     
//                     float size = [imageRep size];
                     NSData *imageData = [NSData data];
                     if ([imageFileName containsString:@"PNG"]) {
                         imageData = UIImagePNGRepresentation(finalImage);
                     } else {
                         imageData = UIImageJPEGRepresentation(finalImage,1);
                     }
                     long long size = [imageData length];
                     NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:finalImage, IQMediaImage, imageFileName, IQMediaFileName, @(size), IQMediaSize, nil];
                     
                     [selectedImages addObject:dict];
                 } else {
                     NSString *imageFileName = [imageRep filename];
                     long long size = [imageRep size];
                     NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:image, IQMediaImage, imageFileName, IQMediaFileName, @(size), IQMediaSize,nil];
                     
                     [selectedImages addObject:dict];
                 }
             }
             else if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo])
             {
                 ALAssetRepresentation *representation = [result defaultRepresentation];
                 
                 NSURL *url = [representation url];
                 long long size = [representation size];
                 NSString *fileName = [representation filename];
                 NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:url, IQMediaAssetURL,fileName, IQMediaFileName, @(size), IQMediaSize, nil];
                 
                 [selectedVideo addObject:dict];
             }
         }
     }];
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    
    if ([selectedImages count])
    {
        [dict setObject:selectedImages forKey:IQMediaTypeImage];
    }
    if ([selectedVideo count])
    {
        [dict setObject:selectedVideo forKey:IQMediaTypeVideo];
    }
    
    if ([self.assetController.delegate respondsToSelector:@selector(assetsPickerController:didFinishMediaWithInfo:)])
    {
        [self.assetController.delegate assetsPickerController:self.assetController didFinishMediaWithInfo:dict];
    }
    
    [self.assetController dismissViewControllerAnimated:YES completion:nil];
}

- (void)longPressGestureRecognizer:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint p = [gestureRecognizer locationInView:self.collectionView];
    
    if (gestureRecognizer.state == UIGestureRecognizerStateBegan)
    {
        NSIndexPath *indexPath = [self.collectionView indexPathForItemAtPoint:p];
        
        if (indexPath)
        {
            NSUInteger totalCount = self.assetsGroup.numberOfAssets;
            NSInteger index = indexPath.row;
            if (self.isReverseOrder) {
                index = totalCount-indexPath.row-1;
            }
            WEAKSELF
            [self.assetsGroup enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:index] options:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
             {
                 if (result)
                 {
                     NSURL *url = [result valueForProperty:ALAssetPropertyAssetURL];
                     
                     if (url)
                     {
                         MPMoviePlayerViewController *controller = [[MPMoviePlayerViewController alloc] initWithContentURL:url];
                         [weakSelf presentMoviePlayerViewControllerAnimated:controller];
                     }
                 }
             }];
        }
    }
}

- (void)unSelectAblumObject:(NSUInteger)currentIndex
{
    NSUInteger totalCount = self.assetsGroup.numberOfAssets;

    NSInteger index = currentIndex;
    if (self.isReverseOrder) {
        index = totalCount - index - 1;
    }
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:index inSection:0];
    IQAssetsCell *cell = (IQAssetsCell *)[self.collectionView cellForItemAtIndexPath:indexPath];
   
    BOOL previouslyContainsIndex = [self.selectedAssets containsIndex:currentIndex];
    if (previouslyContainsIndex) {
        [self.selectedAssets removeIndex:currentIndex];
        
        if (self.assetController.allowsPickingMultipleItems == NO) {
            NSMutableArray *selectedVideo = [[NSMutableArray alloc] init];
            NSMutableArray *selectedImages = [[NSMutableArray alloc] init];
            
            [self.assetsGroup enumerateAssetsAtIndexes:self.selectedAssets options:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
                
                if (result)
                {
                    if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
                    {
                        CGImageRef imageRef = [[result defaultRepresentation] fullScreenImage];
                        UIImage *image = [UIImage imageWithCGImage:imageRef];
                        long long size = [[result defaultRepresentation] size];
                        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:image,IQMediaImage, @(size), IQMediaSize, nil];
                        
                        [selectedImages addObject:dict];
                    }
                    else if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo])
                    {
                        ALAssetRepresentation *representation = [result defaultRepresentation];
                        NSURL *url = [representation url];
                        long long size = [representation size];
                        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:url,IQMediaAssetURL, @(size), IQMediaSize, nil];
                        
                        [selectedVideo addObject:dict];
                    }
                }
            }];
            
            NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
            
            if ([selectedImages count]) [dict setObject:selectedImages forKey:IQMediaTypeImage];
            if ([selectedVideo count])  [dict setObject:selectedVideo forKey:IQMediaTypeVideo];
            
            if ([self.assetController.delegate respondsToSelector:@selector(assetsPickerController:didFinishMediaWithInfo:)])
            {
                [self.assetController.delegate assetsPickerController:self.assetController didFinishMediaWithInfo:dict];
            }
            
            [self.assetController dismissViewControllerAnimated:YES completion:nil];
        }
        else
        {
            WEAKSELF
            [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
                
                if ([weakSelf.selectedAssets count] > 0) {
                    weakSelf.confirmBtn.enabled = YES;
                    weakSelf.preViewBtn.enabled = YES;
                    
                    weakSelf.confirmBtn.backgroundColor = [EPColor epColor_Blue];
                    [weakSelf.confirmBtn setTitle:[NSString stringWithFormat:@"选择(%lu)",(unsigned long)[weakSelf.selectedAssets count]] forState:UIControlStateNormal];
                    
                    if (weakSelf.isOriginalPic == YES) {
                        weakSelf.originalBtn.selected = YES;
                        
                        NSString *originalBtnName = @"原图";
                        float totalSize = [weakSelf getSelectedSize];
                        if (totalSize > 0) {
                            originalBtnName = [NSString stringWithFormat:@"原图(%@)",[FormatUtil stringFromSize:[weakSelf getSelectedSize]]];
                        }
                        [weakSelf.originalBtn setTitle:originalBtnName forState:UIControlStateSelected];
                        
                    } else {
                        weakSelf.originalBtn.selected = NO;
                    }
                    
                }  else   {
                    if (weakSelf.isOriginalPic == YES) {
                        weakSelf.originalBtn.selected = YES;
                        [weakSelf.originalBtn setTitle:@"原图" forState:UIControlStateSelected];
                    } else {
                        weakSelf.originalBtn.selected = NO;
                    }
                    
                    weakSelf.confirmBtn.enabled = NO;
                    weakSelf.preViewBtn.enabled = NO;
                    
                    weakSelf.confirmBtn.backgroundColor = [UIColor lightGrayColor];
                    weakSelf.title = [weakSelf.assetsGroup valueForProperty:ALAssetsGroupPropertyName];
                }
                
                cell.checkmarkView.image = [UIImage imageNamed:@"camera_uncheck"];
                
            } completion:NULL];
        }
        
    }
}

- (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)size {
    //不符合规格：
    if (image == nil || image.size.width <= 0 || image.size.height <= 0) {
        return image;
    }
    
    if (size.width <= 0 || size.height <= 0) {
        return image;
    }
    
    float h1 = image.size.height;
    float w1 = image.size.width;
    double ratio = h1/w1;
    
    //设置初始值：
    double h2 = h1;
    double w2 = w1;
    
    if (h2 > size.height) {
        h2 = size.height;
        w2 = h2 / ratio;
    }
    
    if (w2 > size.width) {
        w2 = size.width;
        h2 = w2 * ratio;
    }
    
    UIImage *finalImage = [GlobalUtil scaleImage:image toResolution:CGSizeMake(w2, h2)];
    return finalImage;
}

#pragma mark - UICollectionViewFlowLayoutDelegate

//- (CGSize) collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
//{
//    return CGSizeMake((UI_SCREEN_WIDTH - 2.0)/3, (UI_SCREEN_WIDTH - 2.0)/3);
//    
////    __block CGSize thumbnailSize = CGSizeMake(80, 80);
////
////    NSUInteger totalCount = self.assetsGroup.numberOfAssets;
////    NSInteger index = indexPath.row;
////    if (self.isReverseOrder) {
////        index = totalCount-indexPath.row-1;
////    }
////
////    [self.assetsGroup enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:index] options:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
////     {
////         if (result)
////         {
////             thumbnailSize = [[result defaultRepresentation] dimensions];
////             CGFloat deviceCellSizeConstant = ((UICollectionViewFlowLayout*)collectionViewLayout).itemSize.height;
////             thumbnailSize = CGSizeMake((thumbnailSize.width*deviceCellSizeConstant)/thumbnailSize.height, deviceCellSizeConstant);
////         }
////         else
////         {
////             *stop = YES;
////         }
////     }];
//
//    return thumbnailSize;
//}

#pragma mark - UICollectionViewDataSource methods

- (NSInteger)collectionView:(UICollectionView *)view numberOfItemsInSection:(NSInteger)section;
{
    return self.assetsGroup.numberOfAssets;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)cv cellForItemAtIndexPath:(NSIndexPath *)indexPath;
{
    IQAssetsCell *cell = [cv dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
    
    NSUInteger totalCount = self.assetsGroup.numberOfAssets;
    NSInteger index = indexPath.row;
    if (self.isReverseOrder) {
        index = totalCount-indexPath.row-1;
    }
    
    [self.assetsGroup enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:index] options:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop)
     {
         if (result)
         {
             CGImageRef thumbnail = [result aspectRatioThumbnail];
             UIImage *imageThumbnail = [UIImage imageWithCGImage:thumbnail];
             cell.imageViewAsset.image = imageThumbnail;
             
             if ([result valueForProperty:ALAssetPropertyType] == ALAssetTypeVideo && ([result valueForProperty:ALAssetPropertyDuration] != ALErrorInvalidProperty))
             {
                 NSNumber *duration = [result valueForProperty:ALAssetPropertyDuration];
                 NSUInteger seconds = [duration doubleValue];

                 {
                     NSUInteger totalMinutes = seconds/60;
                     NSUInteger totalSeconds = ((NSUInteger)seconds)%60;
                     
                     CGFloat reminder = seconds-(totalMinutes*60)-totalSeconds;
                     
                     totalSeconds+=roundf(reminder);
                     
                     if (totalSeconds>= 60)
                     {
                         totalMinutes++;
                         totalSeconds = 0;
                     }
                     
                     cell.labelDuration.text = [NSString stringWithFormat:@"%ld:%02ld",(long)totalMinutes,(unsigned long)totalSeconds];
                     cell.labelDuration.hidden = NO;
                 }
             }
             else if ([result valueForProperty:ALAssetPropertyType] == ALAssetTypePhoto)
             {
                 cell.labelDuration.hidden = YES;
             }
         }
     }];
    
    BOOL selected = [self.selectedAssets containsIndex:index];

//    cell.checkmarkView.alpha = selected?1.0:0.0;
    UIImage *image = selected?[UIImage imageNamed:@"camera_check"]:[UIImage imageNamed:@"camera_uncheck"];
    cell.checkmarkView.image = image;

    return cell;
}

#pragma mark - UICollectionViewDelegate methods

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    IQAssetsCell *cell = (IQAssetsCell *)[collectionView cellForItemAtIndexPath:indexPath];
    
    NSUInteger totalCount = self.assetsGroup.numberOfAssets;
    NSInteger index = indexPath.row;
    if (self.isReverseOrder) {
        index = totalCount-indexPath.row - 1;
    }
    
    BOOL previouslyContainsIndex = [self.selectedAssets containsIndex:index];
    
    if (previouslyContainsIndex) {
        [self.selectedAssets removeIndex:index];
    } else {
        if (self.selectedAssets.count == self.maximumNumberOfSelection) {
            if (self.isShowAlert) {
                NSString *msg = self.showPromt;
                if ([StringUtil isEmpty:self.showPromt]) {
                    msg = [NSString stringWithFormat:@"最多选择%ld张图片",self.maximumNumberOfSelection];
                }
                [ToastView showMsg:msg inView:self.view];
            }
            return;
        }
        [self.selectedAssets addIndex:index];
    }
    
    
    if (self.assetController.allowsPickingMultipleItems == NO) {
        NSMutableArray *selectedVideo = [[NSMutableArray alloc] init];
        NSMutableArray *selectedImages = [[NSMutableArray alloc] init];
        
        [self.assetsGroup enumerateAssetsAtIndexes:self.selectedAssets options:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            
            if (result)
            {
                if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto])
                {
                    CGImageRef imageRef = [[result defaultRepresentation] fullScreenImage];
                    UIImage *image = [UIImage imageWithCGImage:imageRef];
                    long long size = [[result defaultRepresentation] size];
                    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:image,IQMediaImage, @(size), IQMediaSize, nil];
                    
                    [selectedImages addObject:dict];
                }
                else if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo])
                {
                    ALAssetRepresentation *representation = [result defaultRepresentation];
                    NSURL *url = [representation url];
                    long long size = [representation size];
                    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:url,IQMediaAssetURL, @(size), IQMediaSize, nil];
                    
                    [selectedVideo addObject:dict];
                }
            }
        }];
        
        NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
        
        if ([selectedImages count]) [dict setObject:selectedImages forKey:IQMediaTypeImage];
        if ([selectedVideo count])  [dict setObject:selectedVideo forKey:IQMediaTypeVideo];
        
        if ([self.assetController.delegate respondsToSelector:@selector(assetsPickerController:didFinishMediaWithInfo:)])
        {
            [self.assetController.delegate assetsPickerController:self.assetController didFinishMediaWithInfo:dict];
        }
        
        [self.assetController dismissViewControllerAnimated:YES completion:nil];
    }
    else
    {
        WEAKSELF
        [UIView animateWithDuration:0.2 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            
            if ([weakSelf.selectedAssets count] > 0) {
                weakSelf.confirmBtn.enabled = YES;
                weakSelf.preViewBtn.enabled = YES;
                
                weakSelf.confirmBtn.backgroundColor = [EPColor epColor_Blue];
                [weakSelf.confirmBtn setTitle:[NSString stringWithFormat:@"选择(%lu)",(unsigned long)[self.selectedAssets count]] forState:UIControlStateNormal];
                
                if (weakSelf.isOriginalPic == YES) {
                    weakSelf.originalBtn.selected = YES;
                    
                    NSString *originalBtnName = @"原图";
                    float totalSize = [weakSelf getSelectedSize];
                    if (totalSize > 0) {
                        originalBtnName = [NSString stringWithFormat:@"原图(%@)",[FormatUtil stringFromSize:[self getSelectedSize]]];
                    }
                    [weakSelf.originalBtn setTitle:originalBtnName forState:UIControlStateSelected];
                    
                } else {
                    weakSelf.originalBtn.selected = NO;
                }
                
            }  else   {
                if (weakSelf.isOriginalPic == YES) {
                    weakSelf.originalBtn.selected = YES;
                    [weakSelf.originalBtn setTitle:@"原图" forState:UIControlStateSelected];
                } else {
                    weakSelf.originalBtn.selected = NO;
                }
                
                weakSelf.confirmBtn.enabled = NO;
                weakSelf.preViewBtn.enabled = NO;
                
                weakSelf.confirmBtn.backgroundColor = [UIColor lightGrayColor];
                weakSelf.title = [weakSelf.assetsGroup valueForProperty:ALAssetsGroupPropertyName];
            }
            
            UIImage *image = previouslyContainsIndex?[UIImage imageNamed:@"camera_uncheck"]:[UIImage imageNamed:@"camera_check"];
            cell.checkmarkView.image = image;
            
        } completion:NULL];
    }

}

- (void)movieFinishedCallback:(NSNotification*)aNotification
{
    if ([aNotification.name isEqualToString: MPMoviePlayerPlaybackDidFinishNotification]) {
        NSNumber *finishReason = [[aNotification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey];
        
        if ([finishReason intValue] != MPMovieFinishReasonPlaybackEnded)
        {
            MPMoviePlayerController *moviePlayer = [aNotification object];
            
            
            [[NSNotificationCenter defaultCenter] removeObserver:self
                                                            name:MPMoviePlayerPlaybackDidFinishNotification
                                                          object:moviePlayer];
            [self dismissViewControllerAnimated:YES completion:^{  }];
        }
//        self.collectionView.userInteractionEnabled = YES;
        _isPlayerPlaying = NO;
    }
}


@end
